package daogen

import (
	"errors"
	"fmt"
	"path/filepath"
	"strings"
	"text/template"

	"gitee.com/realjf/wob/tools/bctl/util/pathx"
	"github.com/logrusorgru/aurora"
	"github.com/urfave/cli"
)

const daoTemplate = `
package dao

import "{{.modulePath}}/dao/dbs"

var (
	{{.camelName}}Model {{.camelName}}DAO
)

func init() {
	{{.camelName}}Model = New{{.camelName}}Model(dbs.Mongo)
}

type {{.camelName}}DAO interface {
}

type {{.lowerCamelName}}Model struct {
	db *dbs.MongoModel
}

func New{{.camelName}}Model(mongo *dbs.MongoModel) {{.camelName}}DAO {
	return &{{.lowerCamelName}}Model{db: mongo}
}
`

// ApiCommand create api template file
func DaoCommand(c *cli.Context) error {
	daoFile := c.String("o")
	if len(daoFile) == 0 {
		return errors.New("missing -o")
	}
	fp, err := pathx.CreateIfNotExist(daoFile)
	if err != nil {
		return err
	}
	defer fp.Close()

	home := c.String("home")
	if len(home) > 0 {
		pathx.RegisterBctlHome(home)
	}

	text, err := pathx.LoadTemplate(category, daoTemplateFile, daoTemplate)
	if err != nil {
		return err
	}

	baseName := pathx.FileNameWithoutExt(filepath.Base(daoFile))
	if strings.HasSuffix(strings.ToLower(baseName), "-dao") {
		baseName = baseName[:len(baseName)-4]
	} else if strings.HasSuffix(strings.ToLower(baseName), "dao") {
		baseName = baseName[:len(baseName)-3]
	}

	t := template.Must(template.New("etcTemplate").Parse(text))
	if err := t.Execute(fp, map[string]string{
		"gitUser":        getGitName(),
		"gitEmail":       getGitEmail(),
		"serviceName":    baseName,
		"camelName":      CamelString(baseName),
		"lowerCamelName": LowerCamelString(baseName),
		"modulePath":     getModulePath(),
	}); err != nil {
		return err
	}

	fmt.Println(aurora.Green("Done."))
	return nil
}
